<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span style="line-height: 32px">分社配置</span>
                <el-button
                        style="float: right;"
                        type="primary"
                        icon="el-icon-plus"
                        size="small"
                        v-if="userButtonIds.indexOf('baseSet.branch.add') != -1"
                        @click="addbBranchButton">新增分社
                </el-button>
            </div>
            <el-table
                    :data="branchs"
                    border
                    size="small"
                    :header-cell-style="tableHeaderStyle"
                    style="width: 100%">
                <el-table-column
                        fixed
                        type="index"
                        label="No."
                        align="center"
                        header-align="center"
                        width="100">
                    <template slot-scope="scope">
                        {{ (page.pageNum - 1) * page.pageSize + scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column
                        prop="dataName"
                        label="分社"
                        align="center"
                        header-align="center"
                        width="300">
                </el-table-column>
                <el-table-column
                        align="center"
                        header-align="center"
                        label="分社成员">
                    <template slot-scope="scope">
                        <span v-for="(item,index) in scope.row.branchContactList" :key="index">
                               {{index == scope.row.branchContactList.length-1 ? item.contactName : item.contactName+'；'}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column
                        fixed="right"
                        label="操作"
                        align="center"
                        header-align="center"
                        v-if="userButtonIds.indexOf('baseSet.branch.edit') != -1 || userButtonIds.indexOf('baseSet.branch.delete') != -1"
                        width="250">
                    <template slot-scope="scope">
                        <el-button
                                @click="editBranchButton(scope.row)"
                                type="text"
                                v-if="userButtonIds.indexOf('baseSet.branch.edit') != -1"
                                size="small">编辑
                        </el-button>
                        <el-button
                                @click="deletedBranchButton(scope.row.id)"
                                type="text"
                                v-if="userButtonIds.indexOf('baseSet.branch.delete') != -1"
                                size="small">移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页-->
            <div style="text-align:right;margin-top: 20px">
                <el-pagination
                        background
                        layout="prev, pager, next"
                        :page-size="page.pageSize"
                        @current-change="changePageCurrent"
                        :total="page.pageCount">
                </el-pagination>
            </div>


            <el-drawer
                    title="新增分社"
                    size="32%"
                    :visible.sync="addDrawerFlag"
                    :direction="direction">
                <div class="app-container drawer-div">
                    <el-form
                            :model="branch"
                            ref="dynamicValidateForm_add"
                            label-position="right"
                            label-width="100px"
                            class="demo-dynamic"
                            size="small">
                        <el-form-item
                                prop="dataName"
                                label="分社名称"
                                :rules="[
                                  { required: true, message: '请输入分社名称', trigger: 'blur' },
                                  {  max: 200, message: '最多200个字符' }]">
                            <el-input v-model.trim="branch.dataName" maxLength="200" placeholder="请输入分社名称"></el-input>
                        </el-form-item>
                        <el-form-item
                                v-for="(item, index) in branch.branchContactList"
                                :label="'分社成员' + (index+1)"
                                :key="item.key"
                                :prop="'branchContactList.' + index + '.contactName'"
                                :rules="[
                                {required: true, message: '请输入分社成员', trigger: 'blur'},
                                {min: 0,max: 50, message: '最多50个字符' }]">
                            <el-input
                                    v-model.trim="item.contactName"
                                    maxLength="50"
                                    placeholder="请输入分社成员"
                                    style="width: 50%">
                            </el-input>
                            <el-button @click.prevent="removeDomain(item,index)" type="danger" icon="el-icon-minus"
                                       style="float: right;margin-right: 10px"></el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="addDomain" type="primary" icon="el-icon-plus"></el-button>
                        </el-form-item>

                    </el-form>
                </div>
                <div class="demo-drawer__footer">
                    <el-button type="primary" @click="addbranchSubmit('dynamicValidateForm_add')">提交</el-button>
                    <el-button @click="cancelDrawer('dynamicValidateForm_add')" style="">取消</el-button>
                </div>
            </el-drawer>

            <el-drawer
                    title="编辑分社"
                    size="32%"
                    :visible.sync="editDrawerFlag"
                    @close="editDrawerClose"
                    :direction="direction">
                <div class="app-container drawer-div">
                    <el-form
                            :model="branch"
                            ref="dynamicValidateForm_edit"
                            label-position="right"
                            label-width="100px"
                            class="demo-dynamic"
                            size="small">
                        <el-form-item
                                prop="dataName"
                                label="分社名称"
                                :rules="[
                                    { required: true, message: '请输入分社名称', trigger: 'blur' },
                                    {  max: 200, message: '最多200个字符' }]">
                            <el-input v-model.trim="branch.dataName" maxLength="200" placeholder="请输入分社名称"></el-input>
                        </el-form-item>
                        <el-form-item
                                v-for="(item, index) in branch.branchContactList"
                                :label="'分社成员' + (index+1)"
                                :key="item.key"
                                :prop="'branchContactList.' + index + '.contactName'"
                                :rules="[
                                    {required: true, message: '请输入成员名称', trigger: 'blur'},
                                    {min: 0,max: 50, message: '最多50个字符' }]">
                            <el-input
                                    v-model.trim="item.contactName"
                                    maxLength="50"
                                    placeholder="请输入分社成员"
                                    style="width: 50%">
                            </el-input>
                            <el-button @click.prevent="removeDomain(item,index)" type="danger" icon="el-icon-minus"
                                       style="float: right;margin-right: 10px"></el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="addDomain" type="primary" icon="el-icon-plus"></el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="demo-drawer__footer">
                    <el-button type="primary" @click="editbranchSubmit('dynamicValidateForm_edit')">提交</el-button>
                    <el-button @click="cancelDrawer('dynamicValidateForm_edit')" style="">取消</el-button>
                </div>
            </el-drawer>
        </el-card>

    </div>
</template>


<script>
import {Message} from 'element-ui'
import {tableHeaderStyle, } from '@/utils/constant'
import {http_branch_list, http_branch_add, http_branch_edit, http_branch_deleted} from '@/api/branc'


export default {
    data() {

        return {
            tableHeaderStyle: tableHeaderStyle,
            userButtonIds: JSON.parse(localStorage.getItem("user")).buttonIds,
            addDrawerFlag: false,
            editDrawerFlag: false,
            direction: 'rtl',
            branchs: [],
            branch: {
                branchContactList: [{
                    contactName: null,
                    key: null,
                }],
            },
            branchContacts: [],
            branchContact: {},
            page: {
                pageNum: null,
                pageSize: null,
                pageCount: null,
            },

            dynamicValidateForm: {
                domains: [{
                    value: ''
                }],
                email: ''
            },

        }
    },
    methods: {
        selectBranchList() {
            http_branch_list(this.page).then(result => {
                const {data} = result
                this.branchs = data.records
                this.page = {
                    pageNum: data.current,
                    pageSize: data.size,
                    pageCount: data.total,
                }
            })
        },
        addBranch() {
            http_branch_add(this.branch).then(result => {
                const {message, stateCode} = result
                // console.log("result: ", result)
                if (stateCode == '0000') {
                    Message.success(message)
                    this.addDrawerFlag = false
                    this.selectBranchList()
                } else {
                    Message.error(message)
                }
            })
        },
        editBranch() {
            http_branch_edit(this.branch).then(result => {
                const {message, stateCode} = result
                if (stateCode == '0000') {
                    Message.success(message)
                    this.editDrawerFlag = false
                    this.selectBranchList()
                } else {
                    Message.error(message)
                }
            })
        },
        deletedBranch(id) {
            http_branch_deleted(id).then(result => {
                const {message, stateCode} = result
                // console.log("result: ", result)
                if (stateCode == '0000') {
                    Message.success(message)
                    this.selectBranchList()
                } else {
                    Message.error(message)
                }
            })
        },
        handleClick(row) {
            // console.log(row);
        },
        editDrawer() {
            this.drawer = true
        },
        removeDomain(item, index) {
            // console.log(this.branch.branchContactList)
            // console.log(this.branch.branchContactList.length)
            this.$nextTick(() => {
                this.branch.branchContactList.splice(index, 1)
                this.userList.splice(index, 1)
            })

            // console.log(this.branch.branchContactList)
            // console.log(this.branch.branchContactList.length)
            // this.sortIndexs.splice(index,1)
            // var index = this.branch.branchContactList.indexOf(item)
            // if (index !== -1) {
            //     this.branch.branchContactList.splice(index, 1)
            //     this.userList.splice(index, 1)
            // }
        },
        addDomain() {
            // this.sortIndexs.push(this.sortIndexs.length+1)

            this.branch.branchContactList.push({
                contactName: "",
                key: Date.now(),
                contactId: ''
            });

        },
        addbBranchButton() {
            if (this.$refs['dynamicValidateForm_add'] != undefined) {
                this.$refs['dynamicValidateForm_add'].clearValidate();
            }
            this.branch = {
                branchContactList: [{
                    contactName: null,
                    key: null,
                }],
            }
            this.addDrawerFlag = true
        },
        editBranchButton(entity) {
            if (this.$refs['editDrawerFlag'] != null) {
                this.$refs['editDrawerFlag'].clearValidate()
            }
            this.branch = Object.assign({}, entity)

            var userList = []
            this.$nextTick(() => {
                entity.branchContactList.map((item, index) => {
                    userList[index] = item
                    userList[index].userId = item.contactId
                    this.branch.branchContactList[index] = item
                })
                this.userList = userList
            })
            this.editDrawerFlag = true
        },
        deletedBranchButton(id) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deletedBranch(id)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        addbranchSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.addBranch()
                } else {
                    // console.log('error submit!!');
                    return false;
                }
            });
        },
        editbranchSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let isPass = false
                    this.branch.branchContactList.forEach((b, i) => {
                        if (b.contactId != null && b.contactId != '') {
                            isPass = true
                        }
                    })
                    if (isPass == false) {
                        return Message.warning("请添加联系人")
                    }
                    this.editBranch()
                } else {
                    // console.log('error submit!!');
                    return false;
                }
            });
        },
        cancelDrawer() {
            this.addDrawerFlag = false
            this.editDrawerFlag = false
        },
        changePageCurrent(val) {
            this.page.pageNum = val
            this.selectBranchList()
        },
        editDrawerClose() {
            this.selectBranchList()
        }
    },
    created() {
        this.selectBranchList()
    }
}
</script>


<style>
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}

.box-card {
    width: 100%;
}

.el-drawer__header span:focus {
    outline: 0 !important;
}


.demo-drawer__footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background-color: white;
    text-align: center;
}

.drawer-div {
    height: 83vh;
    overflow-y: auto
}
</style>

